package com.gis.visualization.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gis.visualization.config.exceptionhandler.VisException;
import com.gis.visualization.entity.HistorySummary;
import com.gis.visualization.service.HistorySummaryService;
import com.gis.visualization.service.VideoService;
import com.gis.visualization.utils.imageoss.ConstantPropertiesUtils;
import com.gis.visualization.utils.video.InitVodClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    HistorySummaryService summaryService;

    //    上传视频到阿里云
    @Override
    public String uploadVideo(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();//上传文件流
            String originalFilename = file.getOriginalFilename();//上传文件原始名称
            //上传之后显示名称
            String title = originalFilename.substring(0, originalFilename.lastIndexOf("."));

            UploadStreamRequest request = new UploadStreamRequest(
                    ConstantPropertiesUtils.ACCESS_KEY_ID,
                    ConstantPropertiesUtils.ACCESS_KEY_SECRET,
                    title, originalFilename, inputStream);

            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);

            //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。
            // 其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
            String videoId = response.getVideoId();
            if (!response.isSuccess()) {
                String errorMessage = "阿里云上传错误：" + "code：" + response.getCode() + ", message：" + response.getMessage();
//                log.warn(errorMessage);
                if (StringUtils.isEmpty(videoId)) {
                    throw new VisException(20001, errorMessage);
                }
            }
            return videoId;
        } catch (IOException e) {
            throw new VisException(20001, "视频上传失败");
        }
    }

    @Override
    public void removeALYVideo(String videoId) {
//        初始化对象
        DefaultAcsClient client = InitVodClient.initVodClient(
                ConstantPropertiesUtils.ACCESS_KEY_ID,
                ConstantPropertiesUtils.ACCESS_KEY_SECRET);
//        初始化 删除请求
        DeleteVideoRequest request = new DeleteVideoRequest();
//        设置视频id
        request.setVideoIds(videoId);
        try {
//            调用初始化的方法实现删除
            client.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new VisException(20001, "删除视频失败");
        }
    }

    @Override
    public Map<String, String> getPlayAuth(String figureId) {
        LambdaQueryWrapper<HistorySummary> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HistorySummary::getId,figureId);
        wrapper.select(HistorySummary::getVideoSourceId);
        HistorySummary one = summaryService.getOne(wrapper);
        //判断人物总结是否存在
        if (one == null){
            throw new VisException(20001,"没有对应的该人物的视频");
        }
        String vid = one.getVideoSourceId();
        //判断视频id是否存在
        if(StrUtil.isEmpty(vid)){
            throw new VisException(20001,"没有对应的该人物的视频");
        }
        //获取阿里云存储相关常量
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;

        //初始化
        DefaultAcsClient client =  InitVodClient.initVodClient(accessKeyId, accessKeySecret);

        //请求
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(vid);

        //响应
        GetVideoPlayAuthResponse response = null;
        try {
            response = client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new VisException(20001,"获取凭证失败");
        }

        //得到播放凭证
        String playAuth = response.getPlayAuth();
        Map<String,String> videoMap = MapUtil.newHashMap();
        videoMap.put("vid",vid);
        videoMap.put("playAuth",playAuth);
        return videoMap;
    }

    // @Override
    // public String getVideoId(String figureId) {
    //     LambdaQueryWrapper<HistorySummary> wrapper = new LambdaQueryWrapper<>();
    //     wrapper.eq(HistorySummary::getId,figureId);
    //     wrapper.select(HistorySummary::getVideoSourceId);
    //     HistorySummary one = summaryService.getOne(wrapper);
    //     return StrUtil.isEmpty(one.getVideoSourceId()) ?"":one.getVideoSourceId();
    // }
}
